package com.example.Interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.Anno.Interceptor;
import com.example.utils.redisutils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import com.example.utils.jwtutil;

import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor{
    final
    redisutils redisutils;

    public LoginInterceptor(redisutils redisutils) {
        this.redisutils = redisutils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod))
        {
            return true;
        }

        /*获取handlermethod对象*/
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        /*获取拦截的类*/
        Class<?> controller = handlerMethod.getBeanType();
        /*获取注解*/
        Interceptor annotation = controller.getAnnotation(Interceptor.class);
        Interceptor annotation1 = handlerMethod.getMethod().getAnnotation(Interceptor.class);

        if (annotation1==null&&annotation==null) {
            return  true;
        }


        String token = request.getHeader("token");

        try {
            Claims claims = jwtutil.parser(token, "key");
            String id = claims.get("id").toString();
            String s = redisutils.get(id);
            if (s==null) {
                throw  new RuntimeException("token过期了");
            }
            else {
              JSONObject loginUser= JSON.parseObject(s);
                Long endTime = (Long) loginUser.get("endTime");
                if ((endTime-System.currentTimeMillis())<=20*60*1000)
                {
//                   /*小于20分钟，覆盖之前的*/
                    redisutils.setEx(id,loginUser.toString(),System.currentTimeMillis()+60*60*1000, TimeUnit.MILLISECONDS);
                }


                return true;
            }


        } catch (Exception e) {
            response.setStatus(401);
            throw new RuntimeException(e);
        }

    }
}
